#include<iostream>
#include<assert.h>
using namespace std;
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<cstring>


int main(){
    int fds[2];
    int n = pipe(fds);
    assert(n==0);

    pid_t id = fork();
    assert(id >= 0);
    if(id == 0){
        //子进程：用来写数据
        close(fds[0]);
        //开始写入
        int cnt = 0;
        char buffer[1024];
        const char* arr = "我正在给你发消息";
        while(true){
            cnt++;
            snprintf(buffer,sizeof buffer,"我是子进程，%s,pid:%d,cnt:%d\n",arr,getpid(),cnt);
            write(fds[1],buffer,sizeof(buffer));
            //close(fds[1]);//写一点数据就关闭
            //cout<<"子进程已经关闭写端"<<endl;
            //sleep(1);
            //sleep(1000);
            //exit(1);
        }
        close(fds[1]);
        exit(0);
    }

    //父进程：读取数据
    close(fds[1]);  
    //sleep(1000);
    while(true){
        char buffer[1024];
        cout<<"AAAAAAAAAAAAAAAAAA"<<endl;
        ssize_t s = read(fds[0],buffer,sizeof(buffer)-1);
        cout<<"BBBBBBBBBBBBBBBBB"<<endl;
        if(s>0) {
            buffer[s] = 0;//手动添加\0
            cout<<"#:"<<buffer<<endl;
            break;
        }else if(s == 0){
            cout<<"read:"<<s<<endl;
            break;
        }
    }

    close(fds[0]);
    cout<<"父进程关闭读端"<<endl;
    int status = 0;
    //进程等待
    int ret = waitpid(id,&status,0);
    assert(ret==id);
    cout<<"pid->"<<ret<<":"<<(status & 0x7F)<<endl;


    return 0;
}